package nc.bs.pub.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

import nc.bs.common.projectFAUtils;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.NCLocator;
import nc.bs.ic.pub.env.ICBSContext;
import nc.bs.pub.compiler.AbstractCompiler2;
import nc.itf.ic.m45.self.IPurchaseInMaintain;
import nc.itf.ic.m4d.IMaterialOutMaintain;
import nc.itf.pu.m422x.IStoreReqAppClose;
import nc.itf.uif.pub.IUifService;
import nc.jdbc.framework.processor.ArrayListProcessor;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.pubitf.pu.m422x.api.IStoreReqAppQueryAPI;
import nc.pubitf.pu.m422x.pubquery.IStoreReqPubQuery;
import nc.vo.bc.pub.util.StringUtil;
import nc.vo.ic.m45.entity.BillCPVO;
import nc.vo.ic.m45.entity.PurchaseInBodyVO;
import nc.vo.ic.m4d.entity.MaterialOutBodyVO;
import nc.vo.ic.m4d.entity.MaterialOutVO;
import nc.vo.ic.pub.pf.ICPFParameter;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pu.m422x.entity.StoreReqAppItemVO;
import nc.vo.pu.m422x.entity.StoreReqAppVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.compiler.PfParameterVO;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.trade.billsource.LightBillVO;
import nc.vo.trade.billsource.LinkQueryType;

public class N_4D_DELETE extends AbstractCompiler2 {
	private Hashtable m_methodReturnHas = new Hashtable();
	private Hashtable m_keyHas = null;
	private final  String message="Y";
	private String billNO = "";
	private String billFinderClassname = "nc.impl.pubapp.linkquery.BillTypeSetBillFinder";
	private static IUifService service = (IUifService)NCLocator.getInstance().lookup(IUifService.class);
	private IStoreReqPubQuery isq	=NCLocator.getInstance().lookup(IStoreReqPubQuery.class);
	private BaseDAO basedao = new BaseDAO();
	public Object runComClass(PfParameterVO vo) throws BusinessException {
		try {
			super.m_tmpVo = vo;
			ICBSContext context = new ICBSContext();
			context.setICPFParameter((ICPFParameter) this.getUserObj());
			MaterialOutVO[] inVOs = (MaterialOutVO[]) ((MaterialOutVO[]) this.getVos());
			
			List<String> checklist = new ArrayList<String>();
			for(MaterialOutVO inVO : inVOs) {
				MaterialOutBodyVO[] inbvos = inVO.getBodys();
				for(MaterialOutBodyVO inbvo : inbvos) {
					String csourcebillbid = inbvo.getCsourcebillbid();
					String checksql = "select h.vbillcode from ic_transform_b b left join ic_transform_h h on h.cspecialhid = b.cspecialhid "
							+ " where b.dr = 0 and b.vbdef1 = '"+csourcebillbid+"'"; 
					String billcode = (String) new BaseDAO().executeQuery(checksql,new ColumnProcessor());
					if(billcode != null && !"".equals(billcode) && !checklist.contains(billcode)) {
					checklist.add(billcode);
					}
				}
			}
			
			if(checklist != null && checklist.size() > 0) {
				ExceptionUtils.wrappBusinessException("形态转换单"+checklist+"未删除，请检查！");
			}
			
			//lhw 231208  login
			new projectFAUtils().projectDataApprove("ic_material_h",inVOs, "delete");
			//end
			
			//判断是否为红冲单，如是，将被红冲数量回写到来源材料出�?
			returnNum(inVOs);
			
			// 物资�?求主数量回写集合获取
			Map<String, UFDouble> nnum422xmap = updateNumber(inVOs);
			//删除指定
			((IMaterialOutMaintain) NCLocator.getInstance().lookup(IMaterialOutMaintain.class)).delete(inVOs);;
			// 物资�?求主数量回写
			for (Entry<String, UFDouble> item : nnum422xmap.entrySet()) {
				String sql = "update po_storereq_b set naccuoutnum=nvl(naccuoutnum,0.00000000)+" + item.getValue()
						+ "  where pk_storereq_b='" + item.getKey() + "' ";
				basedao.executeUpdate(sql);
			}
			//callK(inVOs);
			return null;
		} catch (Exception var4) {
			ExceptionUtils.marsh(var4);
			return null;
		}
	}



	public String getCodeRemark() {
		return NCLangRes4VoTransl.getNCLangRes().getStrByID("4008003_0", "04008003-0108");
	}

	private void setParameter(String key, Object val) {
		if (this.m_keyHas == null) {
			this.m_keyHas = new Hashtable();
		}

		if (val != null) {
			this.m_keyHas.put(key, val);
		}

	}
	
	/**
	 * 
	 * @param aggvos
	 */
	private void returnNum(MaterialOutVO[] aggvos) throws DAOException {
		Map<String,UFDouble> pks = new HashMap<String,UFDouble>();
		for (int i = 0; i < aggvos.length; i++) {
			//	非红冲单据不处理
			if(aggvos[i].getHead().getNtotalnum().compareTo(UFDouble.ZERO_DBL)>=0) {
				continue;
			}
			MaterialOutBodyVO[] bvos = aggvos[i].getBodys();
			for (int j = 0; j < bvos.length; j++) {
//				实发数量不为空，记录来源主键
				if(bvos[j].getNnum()!=null) {
					if(pks.get(bvos[j].getCsourcebillbid())==null){
						pks.put(bvos[j].getCsourcebillbid(),bvos[j].getNnum().abs());
					}else {
						pks.put(bvos[j].getCsourcebillbid(),bvos[j].getNnum().add(pks.get(bvos[j].getCsourcebillbid())));
					}
				}
			}
		}
		if(pks.size()>0) {
			StringBuffer sb = new StringBuffer();
			sb.append("Select * from ic_material_b where cgeneralbid in (");
			for (String pk : pks.keySet()) {
				sb.append("'"+pk+"',");
			}
			sb.deleteCharAt(sb.length()-1).append(")");
			BaseDAO bd = new BaseDAO();
			List<MaterialOutBodyVO> nbvos = (List<MaterialOutBodyVO>)bd.executeQuery(sb.toString(),new BeanListProcessor(MaterialOutBodyVO.class));
			for (int i = 0; i < nbvos.size(); i++) {
				UFDouble num = pks.get(nbvos.get(i).getCgeneralbid());
				UFDouble oldnum = nbvos.get(i).getVbdef1()==null?UFDouble.ZERO_DBL:new UFDouble(nbvos.get(i).getVbdef1());
				if(num.compareTo(oldnum)>0) {
					ExceptionUtils.wrappBusinessException("现累计红冲数量大于单据红冲数量，请检查数据后重试");
				}else {
					nbvos.get(i).setVbdef1(oldnum.sub(num).toString());
				}
			}
			bd.updateVOList(nbvos);
		}
	}
	
	public List<BillCPVO> getNobyId(String id){
		LinkQueryType queryType = LinkQueryType.OnlyQueryBill;
		LightBillVO vo = null;

		try {
			vo = service.queryBillGraph(billFinderClassname, id,"45", queryType);
			if (vo != null && StringUtils.isEmpty(vo.getCode())) {
				vo.setCode(billNO);
			}
		} catch (Exception var9) {
			String message = NCLangRes4VoTransl.getNCLangRes().getStrByID("0020nccloud_0", "0ncc0020001-0277");
			Exception ex = new RuntimeException(var9);
			Throwable cause = ExceptionUtils.unmarsh(ex);
			if (var9 != null && cause.getMessage() != null) {
				message = cause.getMessage();
			}

			ExceptionUtils.wrappBusinessException(message);
		}
		
		List<BillCPVO> list = this.dealVO(vo);
		return list;
		}
	
	public List<BillCPVO> dealVO(LightBillVO vo) {
		if (vo == null) {
			return null;
		} else {
			Map<String, BillCPVO> setAll = new LinkedHashMap();
			this.getSource(vo, setAll);
			List<String> sourceList = ((BillCPVO) setAll.get(vo.getID())).getSourceList();
			this.getForward(vo, setAll);
			((BillCPVO) setAll.get(vo.getID())).setIsForward("0");
			((BillCPVO) setAll.get(vo.getID())).setSourceList(sourceList);
			List<BillCPVO> list = new ArrayList(setAll.values());
			return list;
		}
	}
	
	
	public void getSource(LightBillVO vo, Map<String, BillCPVO> setAll) {
		if (vo != null) {
			BillCPVO flow = new BillCPVO();
			flow.setLightBillVO(vo);
			flow.setIsForward("-1");
			List<String> sourceList = flow.getSourceList();
			if (vo.getSourceBillVOs() == null) {
				if (setAll.get(vo.getID()) == null) {
					setAll.put(vo.getID(), flow);
				}

			} else {
				LightBillVO[] var5 = vo.getSourceBillVOs();
				int var6 = var5.length;

				for (int var7 = 0; var7 < var6; ++var7) {
					LightBillVO sourVO = var5[var7];
					sourceList.add(sourVO.getID());
					this.getSource(sourVO, setAll);
				}

				vo.setSourceMap(new HashMap());
				flow.setSourceList(sourceList);
				setAll.put(vo.getID(), flow);
			}
		}
	}

	public void getForward(LightBillVO vo, Map<String, BillCPVO> setAll) {
		if (vo != null) {
			BillCPVO flow = new BillCPVO();
			flow.setLightBillVO(vo);
			flow.setIsForward("1");
			List<String> forwardList = flow.getForwardList();
			if (vo.getForwardBillVOs() == null) {
				if (setAll.get(vo.getID()) == null) {
					setAll.put(vo.getID(), flow);
				}

			} else {
				LightBillVO[] var5 = vo.getForwardBillVOs();
				int var6 = var5.length;

				for (int var7 = 0; var7 < var6; ++var7) {
					LightBillVO sourVO = var5[var7];
					forwardList.add(sourVO.getID());
					this.getForward(sourVO, setAll);
				}

				vo.setForwardMap(new HashMap());
				flow.setForwardList(forwardList);
				setAll.put(vo.getID(), flow);
			}
		}
	}
	//wxp start
	private void callK(MaterialOutVO[] inVOs) {
	
		
		for (int i = 0; i < inVOs.length; i++) {
			
			
			
			if(null!=inVOs[i].getHead().getVdef2()) {
			if(!inVOs[i].getHead().getVdef2().equals("Y")) {
			    continue;
			}
			}
			MaterialOutBodyVO[] bvos = (MaterialOutBodyVO[]) inVOs[i].getAllChildrenVO();
			
			List<MaterialOutBodyVO> matVoList = Arrays.asList(bvos);
			
			
			matVoList.stream().forEach(ml->{
				//
				String no=ml.getVfirstrowno();
				//获取单据id
				String stno=ml.getCsourcebillbid();
				//获取数量
				UFDouble numberl=ml.getNassistnum();
				if(null==numberl) {
					numberl=new UFDouble(0);
				}
	
			String sql="select ipu.cgeneralhid from ic_purchasein_h ipu left join ic_purchasein_b ipb on ipb.cgeneralhid =ipu.cgeneralhid  where ipb.dr = 0 and  ipb.cgeneralbid='"+stno+"'   ";	
			String column;
			try {
				column = (String) new BaseDAO().executeQuery(sql,new ColumnProcessor());
			
			
			if(column!=null) {
			List<BillCPVO>   billss=getNobyId(column);
			//获取修改的code
			String updateCodez =null;
			for(BillCPVO bvo:billss) {
				LightBillVO lvo=bvo.getLightBillVO();
				if(lvo.getType().equals("422X")) {
					updateCodez =lvo.getCode();
				}
			}
			if(updateCodez!=null) {
				String sqlno="select ipb.vsourcerowno from ic_purchasein_h ipu left join ic_purchasein_b ipb on ipb.cgeneralhid =ipu.cgeneralhid  where ipb.dr = 0 and  ipb.cgeneralbid='"+stno+"'   ";	
				String sno=(String) new BaseDAO().executeQuery(sqlno,new ColumnProcessor());
				  String sqlnumber ="select pk_storereq_b  from po_storereq_b psb LEFT JOIN  po_storereq ps  ON  ps.pk_storereq = psb.pk_storereq  where  psb.dr=0 and ps.vbillcode='"+updateCodez+"' and psb.crowno='"+ sno +"'";  							
				  String sqlb=(String) new BaseDAO().executeQuery(sqlnumber,new ColumnProcessor());
				  UFDouble newnb=numberl;
				  String[] pk=new String[1];
				  pk[0]=sqlb;
				  StoreReqAppItemVO[] sra=isq.queryItemVOByBids(pk);
				  UFDouble nb=new UFDouble(0);
				  if(null!=sra[0].getNaccuoutnum()) {
					   nb=sra[0].getNaccuoutnum();
					
				  }
				  
				  UFDouble oldnb=new UFDouble(nb);
				  newnb=oldnb.sub(numberl);
				
				  if(nb.compareTo(UFDouble.ZERO_DBL)<0) {
					  throw new BusinessException("数据量不对�?�请�?�?");
					  
				  }
				  String  updateSql="update po_storereq_b set naccuoutnum ='"+newnb+"' where pk_storereq_b ='"+sqlb+"' ";	
				  new BaseDAO().executeUpdate(updateSql);
				
			}
			
			
		}
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
			e.printStackTrace();
			}
		
			});
	}
}
	
	public Map<String, UFDouble> updateNumber(MaterialOutVO[] i6vo) {

		String sql = "";
		// 物资�?求表体PK 应反写数�?
		Map<String, UFDouble> nnum422xmap = new HashMap<>();

		// 先遍历行 得出各行应反写数�? 并放入集�?
		for (MaterialOutVO agg : i6vo) {
			if (!"Y".equals(agg.getHead().getVdef2()))
				continue;
			try {

				for (MaterialOutBodyVO bvo : agg.getBodys()) {
					if ("21".equals(bvo.getCfirsttype())) {
						// 根据采购订单表体来源信息查询物资�?求单表体记录
						sql = "select distinct * from (SELECT c.pk_storereq_b,c.nnum,c.naccuoutnum,c.pk_storereq,c.bclose FROM po_order_b a\r\n"
								+ "LEFT JOIN ct_pu_b b ON a.ccontractrowid=b.pk_ct_pu_b\r\n"
								+ "LEFT JOIN po_storereq_b c ON b.csrcbid=c.pk_storereq_b \r\n"
								+ "WHERE c.pk_storereq IS NOT NULL AND a.pk_order_b='" + bvo.getCfirstbillbid()
								+ "'\r\n" + "UNION  \r\n"
								+ "SELECT c.pk_storereq_b,c.nnum,c.naccuoutnum,c.pk_storereq,c.bclose FROM po_order_b a\r\n"
								+ "LEFT JOIN po_praybill_b  b ON b.pk_praybill_b =a.cpraybillbid\r\n"
								+ "LEFT JOIN po_storereq_b c ON b.csourcebid =c.pk_storereq_b \r\n"
								+ "WHERE c.pk_storereq IS NOT NULL AND a.pk_order_b='" + bvo.getCfirstbillbid()
								+ "'\r\n" + "UNION \r\n"
								+ "SELECT c.pk_storereq_b,c.nnum,c.naccuoutnum,c.pk_storereq,c.bclose FROM po_order_b a\r\n"
								+ "LEFT JOIN purp_priceaudit_b  b ON b.pk_priceaudit_b =a.cpriceaudit_bid\r\n"
								+ "LEFT JOIN po_storereq_b c ON b.csrcbid =c.pk_storereq_b \r\n"
								+ "WHERE c.pk_storereq IS NOT NULL AND a.pk_order_b='" + bvo.getCfirstbillbid()
								+ "' "+ "UNION \r\n"
								+ "SELECT c.pk_storereq_b,c.nnum,c.naccuoutnum,c.pk_storereq,c.bclose FROM po_order_b a\r\n"
								+"LEFT JOIN po_storereq_b c ON a.csourcebid =c.pk_storereq_b \r\n"
						        +"WHERE c.pk_storereq IS NOT NULL AND a.pk_order_b='" + bvo.getCfirstbillbid()+"' "
								+ ") a";
						List<Object[]> pk_storereqs = (List<Object[]>) basedao.executeQuery(sql,
								new ArrayListProcessor());
						// 如物资需求单表体记录为空跳过该行
						if (pk_storereqs == null || pk_storereqs.size() <= 0)
							continue;
						// 物资续签 表体PK 主数�? 累计出库主数�? 表头PK 是否关闭
						String pk_storereq_b = pk_storereqs.get(0)[0] == null ? "" : pk_storereqs.get(0)[0].toString();

						UFDouble reqnnum = new UFDouble(
								pk_storereqs.get(0)[1] == null ? "0" : pk_storereqs.get(0)[1].toString());
						UFDouble naccuoutnum = new UFDouble(
								pk_storereqs.get(0)[2] == null ? "0" : pk_storereqs.get(0)[2].toString());

						String pk_storereq = pk_storereqs.get(0)[3] == null ? "" : pk_storereqs.get(0)[3].toString();

						String bclose = pk_storereqs.get(0)[4] == null ? "" : pk_storereqs.get(0)[4].toString();
						UFDouble nnum = bvo.getNnum();

						nnum = nnum.multiply(new UFDouble(-1));
						
						if (nnum422xmap.containsKey(pk_storereq_b)) {
							nnum422xmap.put(pk_storereq_b, nnum422xmap.get(pk_storereq_b).add(nnum));
						} else {
							nnum422xmap.put(pk_storereq_b, nnum);
						}

						bvo.setVbdef1(bvo.getNnum().toString());
						
						// 关闭物资�?求行
						if (!"Y".equals(bclose)
								&& (naccuoutnum.add(nnum422xmap.get(pk_storereq_b))).compareTo(reqnnum) >= 0) {
							IStoreReqAppQueryAPI qrysv = NCLocator.getInstance().lookup(IStoreReqAppQueryAPI.class);
							StoreReqAppVO[] aggvos = qrysv.queryVOByIDs(new String[] { pk_storereq });
							StoreReqAppItemVO itemvo = null;
							for (StoreReqAppItemVO reqitem : aggvos[0].getBVO()) {
								if (reqitem.getPk_storereq_b().equals(pk_storereq_b)) {
									itemvo = reqitem;
									break;
								}
							}
							aggvos[0].setBVO(new StoreReqAppItemVO[] { itemvo });
							if (itemvo != null) {
								IStoreReqAppClose closesv = NCLocator.getInstance().lookup(IStoreReqAppClose.class);
								closesv.rowClose(new StoreReqAppVO[] { aggvos[0] });
							}

						}
						if ("Y".equals(bclose)
								&& (naccuoutnum.add(nnum422xmap.get(pk_storereq_b))).compareTo(reqnnum) <= 0) {
							IStoreReqAppQueryAPI qrysv = NCLocator.getInstance().lookup(IStoreReqAppQueryAPI.class);
							StoreReqAppVO[] aggvos = qrysv.queryVOByIDs(new String[] { pk_storereq });
							StoreReqAppItemVO itemvo = null;
							for (StoreReqAppItemVO reqitem : aggvos[0].getBVO()) {
								if (reqitem.getPk_storereq_b().equals(pk_storereq_b)) {
									itemvo = reqitem;
									break;
								}
							}
							aggvos[0].setBVO(new StoreReqAppItemVO[] { itemvo });
							if (itemvo != null) {
								IStoreReqAppClose closesv = NCLocator.getInstance().lookup(IStoreReqAppClose.class);
								closesv.rowOpen(new StoreReqAppVO[] { aggvos[0] });
							}
						}
					}

				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				ExceptionUtils.wrappBusinessException(e.getMessage());
			}
		}

		return nnum422xmap;
	}
	//end
}